<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, onMounted, h, computed } from 'vue'
import { Search } from '@/components/Search'
import { Table, TableColumn } from '@/components/Table'
import { Form, FormSchema } from '@/components/Form'
import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ChatSidebarPanel } from '@/components/IntelligentChat'
import { ElMessage, ElUpload, ElButton, ElDialog, ElLink } from 'element-plus'
import { Icon } from '@/components/Icon'
import * as XLSX from 'xlsx'
import { IntelligentChat } from '@/components/IntelligentChat'
import { DIFY_API_V1_URL, DIFY_API_KEY, DIFY_API_KEY_changjing1 } from '@/constants/dify'
import { DifyConfig } from '@/api/dify'
import { getAbnormalOrderStatsZg } from '@/api/electricityAbnormal'
import { inject } from 'vue'
import type { ComponentPublicInstance } from 'vue'
interface ChatSidebarInstance extends ComponentPublicInstance {
  openDrawer: () => void
  closeDrawer: () => void
}

const { t } = useI18n()

// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData } = searchMethods

// 多选相关数据
const selectedRows = ref<any[]>([])

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 搜索表单配置
const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  },
  {
    field: 'wkOrderNo',
    label: '工单编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入工单编号'
    }
  },
  {
    field: 'wkOrderStatName',
    label: '工单状态',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择工单状态',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: false,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: [
        { label: '全部', value: '全部' },
        { label: '挂起', value: '挂起' },
        { label: '作废', value: '作废' },
        { label: '归档', value: '归档' },
        { label: '在途', value: '在途' }
      ],
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'field1',
    label: '用电类别',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用电类别'
    }
  },
  {
    field: 'wkOrderType',
    label: '工单类型',
    component: 'Input',
    componentProps: {
      placeholder: '请输入工单类型'
    }
  }
])

// 使用useTable hook进行表格数据管理
const { tableRegister, tableMethods, tableState } = useTable({
  immediate: true, // 立即请求
  fetchDataApi: async () => {
    try {
      // 获取搜索表单数据
      const formData = await getFormData()
      console.log('整改页面formData:', formData)

      // 模拟API请求 - 实际项目中应替换为真实API
      // 这里使用setTimeout模拟网络请求
      return new Promise((resolve) => {
        setTimeout(() => {
          // 这里是模拟数据，实际应该从后端API获取
          // const mockData = [
          //   {
          //     mgtOrgName: '国网湖北省电力公司',
          //     prntMgtOrgName: '武汉供电所',
          //     wkOrderNo: '20250114090530',
          //     wkOrderType: '业扩工单',
          //     wkOrderClass: '低压非居民新装',
          //     procName: '预约',
          //     custNo: '202501140905301',
          //     wkOrderStatName: '在途',
          //     isImportant: '否',
          //     qualityReason: '定期质检'
          //   }
          // ]
          // 从父组件获取质检工单数据
          let mockData: any[] = []

          if (qualityWorkOrders && qualityWorkOrders.value) {
            mockData = qualityWorkOrders.value
          } else {
            // 从localStorage获取数据作为备选
            const savedWorkOrders = localStorage.getItem('qualityWorkOrders')
            if (savedWorkOrders) {
              mockData = JSON.parse(savedWorkOrders)
            } else {
              // 默认数据
              mockData = [
                // {
                //   mgtOrgName: '国网湖北省电力公司',
                //   prntMgtOrgName: '武汉供电所',
                //   wkOrderNo: '20250114090530',
                //   wkOrderType: '业扩工单',
                //   wkOrderClass: '低压非居民新装',
                //   procName: '预约',
                //   custNo: '202501140905301',
                //   wkOrderStatName: '在途',
                //   isImportant: '否',
                //   qualityReason: '定期质检'
                // }
              ]
            }
          }
          // 根据查询条件过滤数据
          const filteredData = mockData.filter((item) => {
            if (formData.mgtOrgName && !item.mgtOrgName.includes(formData.mgtOrgName)) return false
            if (formData.custNo && !item.custNo.includes(formData.custNo)) return false
            if (formData.wkOrderNo && !item.wkOrderNo.includes(formData.wkOrderNo)) return false
            if (formData.wkOrderStatName && item.wkOrderStatName !== formData.wkOrderStatName) return false
            if (formData.wkOrderType && !item.wkOrderType.includes(formData.wkOrderType)) return false
            return true
          })

          // 返回查询结果
          resolve({
            list: filteredData,
            total: filteredData.length
          })
        }, 500)
      })
    } catch (error) {
      return Promise.reject(error)
    }
  }
})

// 从useTable中解构获取数据和状态
const { dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// 表格列配置
const columns = reactive<TableColumn[]>([
  {
    field: '',
    type: 'selection', // 多选列
    width: 60,
    selection: true
  },
  // {
  //   field: 'index',
  //   type: 'index', // 序号列
  //   label: '序号',
  //   width: 60,
  //   fixed: 'left'
  // },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    minWidth: 180
  },
  {
    field: 'wkOrderNo',
    label: '质检工单编号',
    minWidth: 120
  },
  {
    field: 'qlwkOrderNo',
    label: '被质检工单编号',
    minWidth: 120
  },
  {
    field: 'wkOrderType',
    label: '被质检工单类型',
    minWidth: 110
  },
  {
    field: 'wkOrderClass',
    label: '被质检工单分类',
    minWidth: 130
  },
  {
    field: 'isImportant',
    label: '是否重要客户',
    minWidth: 100
  },
  {
    field: 'custNo',
    label: '用户编号',
    minWidth: 90
  },
  {
    field: 'qualityReason',
    label: '质检原因',
    minWidth: 100
  },
  {
    field: 'action',
    label: '操作',
    width: 150,
    fixed: 'right',
    slots: {
      default: ({ row }) => {
        return [
          h(
            ElButton,
            {
              type: 'primary',
              link: true,
              onClick: () => viewDetails(row)
            },
            () => '查看详情'
          )
        ]
      }
    }
  }
])

// 注入父组件提供的数据
const qualityWorkOrders = inject('qualityWorkOrders') as any


// 弹窗-质检表单配置
const qualitySchema = reactive<FormSchema[]>([
  {
    field: 'field1',
    label: '质检标志',
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          // disabled: true,
          label: '合格',
          value: '01'
        },
        {
          label: '不合格',
          value: '02'
        },
        {
          label: '存疑',
          value: '03'
        }
      ]
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'ecCategName',
    label: '质检标签',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择质检标签',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: false,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: [
        {
          label: '红线问题', value: '01', children: [
            { label: '拒绝受理客户报装', value: '0101' },
            { label: '收费问题', value: '0102' },
            { label: '人员服务态度', value: '0103' },
            { label: '服务推诿', value: '0104' }
          ]
        },
        { label: '意思体外循环', value: '02', children: [{ label: '', value: '0201' }] },
        { label: '终止不规范', value: '03', children: [{ label: '', value: '0301' }] },
      ],
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    },
    colProps: {
      span: 12
    }
  },
  {
    field: 'field2',
    label: '是否创建督办',
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          // disabled: true,
          label: '是',
          value: '02'
        },
        {
          label: '否',
          value: '01'
        }
      ]
    },
    colProps: {
      span: 12
    }
  },
  {
    field: 'field6',
    label: '标签描述',
    component: 'Input',
    componentProps: {
      placeholder: ' ',
      type: 'textarea',
      rows: 2
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'field8',
    component: 'Upload',
    label: '',
    componentProps: {
      limit: 3,
      action: 'https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15',
      // fileList: ,
      multiple: true,
      onPreview: (uploadFile) => {
        console.log(uploadFile)
      },
      onRemove: (file) => {
        console.log(file)
      },
      slots: {
        default: () => h(ElLink, { type: 'primary' }, () => '添加附件'),
        tip: () => h('div', { class: 'el-upload__tip' }, '只能上传jpg/png文件，且不超过500kb.')
      }
    }
  }
])
// 弹窗-质检督办
const qualSuperSchema = reactive<FormSchema[]>([
  {
    field: 'field1',
    label: '督办工单分类',
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          // disabled: true,
          label: '服务问题督办',
          value: '01'
        },
        {
          label: '运营质量督办',
          value: '02'
        },
        {
          label: '未立即上线',
          value: '03'
        }
      ]
    },
    colProps: {
      span: 20
    }
  },
  {
    field: 'field2',
    label: '督办内容',
    component: 'Input',
    componentProps: {
      placeholder: ' ',
      type: 'textarea',
      rows: 2
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'field8',
    component: 'Upload',
    label: ' ',
    componentProps: {
      limit: 3,
      action: 'https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15',
      // fileList: ,
      multiple: true,
      onPreview: (uploadFile) => {
        console.log(uploadFile)
      },
      onRemove: (file) => {
        console.log(file)
      },
      slots: {
        default: () => h(ElLink, { type: 'primary' }, () => '添加附件'),
        tip: () => h('div', { class: 'el-upload__tip' }, '只能上传jpg/png文件，且不超过500kb.')
      }
    }
  }
]);
// 弹窗-派单
const dispatchOrderSchema = reactive<FormSchema[]>([
  {
    field: 'field1',
    label: '派单单位',
    component: 'Input',
    componentProps: {
      placeholder: ' ',
      disabled: true,
    },
    colProps: {
      span: 8
    }
  },
  {
    field: 'field2',
    label: '派单部门',
    component: 'Input',
    componentProps: {
      placeholder: ' ',
      disabled: true,
    },
    colProps: {
      span: 8
    }
  },
  {
    field: 'field3',
    label: '派单人员',
    component: 'Input',
    componentProps: {
      placeholder: ' ',
      disabled: true,
    },
    colProps: {
      span: 8
    }
  },
  {
    field: 'field4',
    label: '处理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入处理单位',
    },
    colProps: {
      span: 8
    }
  },
  {
    field: 'field5',
    label: '处理部门',
    component: 'Input',
    componentProps: {
      placeholder: '请输入处理单位',
    },
    colProps: {
      span: 8
    }
  },
  {
    field: 'field6',
    component: 'DatePicker',
    label: '回复截止日期',
    componentProps: {
      placeholder: '请选择回复截止日期',
      type: 'date'
    },
    colProps: {
      span: 8
    }
  },
  {
    field: 'field7',
    label: '派单说明',
    component: 'Input',
    componentProps: {
      placeholder: ' ',
      type: 'textarea',
      rows: 2
    },
    colProps: {
      span: 24
    }
  },
])
// 详情弹窗相关参数
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

// 查看详情
const viewDetails = (row) => {
  console.log('查看详情:', row)
  // ElMessage.success('查看详情功能待实现')
  currentDetail.value = {
    ...row
  }
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

// 处理查询
const handleSearch = async () => {
  // 重置页码到第一页
  currentPage.value = 1
  refresh()
  // ElMessage.success('查询成功')
}

// 暴露方法给父组件
defineExpose({
  handleSearch
})

// 处理重置
const handleReset = async () => {
  // 将重置页面和刷新数据交给Search组件完成
  currentPage.value = 1
  refresh()
}

const { setProps } = tableMethods
// 在组件挂载后注册Search组件
onMounted(() => {
  // 从localStorage加载质检工单数据
  const savedWorkOrders = localStorage.getItem('qualityWorkOrders')
  if (savedWorkOrders) {
    // 更新父组件的数据
    if (qualityWorkOrders) {
      qualityWorkOrders.value = JSON.parse(savedWorkOrders)
    }
  }


  // 设置固定表格高度 437.8
  setProps({
    height: 438
  })
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)

    // 统一设置所有表单项的大小和宽度
    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })
  }
})

// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}
</script>

<template>
  <ContentWrap title="">
    <!-- 搜索表单 - 使用项目封装的Search组件 -->
    <Search ref="searchRef" :schema="schema" label-width="100px" :layout="'bottom'" :button-position="'right'"
      @search="handleSearch" @reset="handleReset" />
    <div></div>

    <!-- 表格 - 使用项目封装的Table组件 -->
    <div style="margin-top:20px">
      <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :loading="tableState.loading.value"
        :data="dataList" :columns="columns" row-key="planNo" height="450" :fit="true" :pagination="{
          total: total,
          pageSize: pageSize,
          currentPage: currentPage,
          pageSizes: [10, 20, 30, 40, 50],
          background: true
        }" style="
        --el-table-border-color: #cdd7d5;
        --el-table-text-color: #171717;
        --el-table-header-text-color: #585858;
      " :header-cell-style="() => ({
        'background-color': '#e5f5f3', // 背景色
        color: '#585858' // 文字颜色
      })" :row-style="tableRowStyle" @register="tableRegister" @selection-change="handleSelectionChange" />
    </div>
  </ContentWrap>

  <!-- 详情弹窗 -->
  <ElDialog v-model="detailDialogVisible" title="详情" width="70%" :before-close="closeDetailDialog" destroy-on-close
    class="detail-dialog" style="">
    <div class="detail-container">
      <div class="detail-section">
        <div class="detail-title">质检工单信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">质检工单编号：</div>
            <div class="detail-value">{{ currentDetail?.wkOrderNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">被质检工单编号：</div>
            <div class="detail-value">{{ currentDetail?.qlwkOrderNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">被质检工单类型：</div>
            <div class="detail-value">{{ currentDetail?.wkOrderType }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">被质检工单分类：</div>
            <div class="detail-value">{{ currentDetail?.wkOrderClass }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">供电单位：</div>
            <div class="detail-value">{{ currentDetail?.mgtOrgName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">供电所：</div>
            <div class="detail-value">{{ currentDetail?.prntMgtOrgName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">是否重要客户：</div>
            <div class="detail-value">{{ currentDetail?.isImportant }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">质检创建时间：</div>
            <div class="detail-value">{{ currentDetail?.createTime || '2025-01-14 09:05:30' }}</div>
          </div>
          <div class="detail-item"></div>
          <div class="detail-item">
            <div class="detail-label">质检原因：</div>
            <div class="detail-value">{{ currentDetail?.qualityReason }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">质检</div>
        <div class="detail-info">
          <Form ref="qualityRef" :schema="qualitySchema" label-width="120px" />
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">质检督办</div>
        <div class="detail-info">
          <Form ref="qualSuperRef" :schema="qualSuperSchema" label-width="120px" />
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">派单</div>
        <div class="detail-info">
          <Form ref="dispatchOrderRef" :schema="dispatchOrderSchema" label-width="120px" />
        </div>
      </div>
      <div class="detail-section-end">
        <div class="detail-buttonGroup">
          <ElButton type="default" @click="() => { }"> 保存 </ElButton>
          <ElButton type="primary" @click="() => { }"> 提交 </ElButton>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style lang="scss" scoped>
.operation-button {
  margin-left: 8px;
}

.mr-5px {
  margin-right: 5px;
}

/* 详情弹窗样式 */
.detail-container {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  padding: 26px 6px 26px 26px;
}

.detail-section {
  padding: 6px;
  border-bottom: 1px solid #999;
}

.detail-section-end {
  padding: 6px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 4px;
  margin-bottom: 6px;
  border-left: 4px solid #009966;
  padding-left: 10px;
}

.detail-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 0 0 0 70px;
}

.detail-item {
  width: 33.333%;
  min-height: 30px;
  display: flex;
  padding: 10px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  // min-width: 130px;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

.detail-buttonGroup {
  width: 100%;
  height: 50px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style>
